package cn.pconline.autoclub.web.admin;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.Promotion;
import cn.pconline.autoclub.entity.PromotionPublish;
import cn.pconline.autoclub.entity.Theme;
import cn.pconline.autoclub.service.PagerService;
import cn.pconline.autoclub.service.PromotionService;
import cn.pconline.autoclub.service.ThemeService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.gelivable.log.GeliLogFacade;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/admin")
public class AdminPromotionController {

    @Autowired
    PromotionService promotionService;
    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private ThemeService themeService;
    private static final Logger log = LoggerFactory.getLogger(AdminPromotionController.class);

    @RequestMapping(value = "/promotion/list.do")
    public String list(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        //sql
        String orderField = env.param("orderField", "create_at");
        String orderDirection = env.param("orderDirection", "desc");
        String name = env.param("name", "").trim();
        String area = env.param("area", "").trim();//provinceName or cityName
        int timeStatus = NumberUtils.toInt(env.param("timeStatus", "").trim(), 0);
        String clubName = env.param("clubName", "").trim();
        String brandName = env.param("brandName", "").trim();
        String seriesName = env.param("seriesName", "").trim();
        String endDate = env.param("endDate", "");
        long themeId = WebUtils.paramLong(req, "themeId", 0);

        int pageNo = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select distinct(promotion.promotion_id) from ").appendSql(geliOrm.getTableName(Promotion.class)).appendSql(" promotion LEFT JOIN ")
                .appendSql(geliOrm.getTableName(PromotionPublish.class)).appendSql(" publish ON promotion.promotion_id = publish.promotion_id ");
        if (StringUtils.isNotBlank(clubName)) {
            sql.appendSql(" LEFT JOIN ");
            sql.appendSql(geliOrm.getTableName(Club.class)).appendSql(" club ON publish.club_id = club.club_id ");
        }
        sql.appendSql(" where 1=1 ");
        if (StringUtils.isNotBlank(name)) {
            sql.appendSql(" and promotion.name like").appendValue("%" + name + "%");
        }
        if (StringUtils.isNotBlank(area)) {  // area
            String[] proCityArray = area.split(";");
            sql.appendSql(" and(");
            for (int i = 0; i < proCityArray.length; i++) {
                String proCity = proCityArray[i];
                sql.appendSql("(publish.province_name like ").appendValue("%" + proCity + "%");
                sql.appendSql(" or publish.city_name like ").appendValue("%" + proCity + "%").appendSql(")");
                if (i < proCityArray.length - 1) {
                    sql.appendSql(" or ");
                }
            }
            sql.appendSql(")");
        }
        if (StringUtils.isNotBlank(brandName)) {    //brand
            String[] brandArray = brandName.split(";");
            sql.appendSql(" and(");
            for (int i = 0; i < brandArray.length; i++) {
                String brand = brandArray[i];
                sql.appendSql("(publish.brand_name like ").appendValue("%" + brand + "%").appendSql(")");
                if (i < brandArray.length - 1) {
                    sql.appendSql(" or ");
                }
            }
            sql.appendSql(")");
        }
        if (StringUtils.isNotBlank(seriesName)) {    //series
            String[] seriesArray = seriesName.split(";");
            sql.appendSql(" and(");
            for (int i = 0; i < seriesArray.length; i++) {
                String series = seriesArray[i];
                sql.appendSql("(publish.series_name like ").appendValue("%" + series + "%").appendSql(")");
                if (i < seriesArray.length - 1) {
                    sql.appendSql(" or ");
                }
            }
            sql.appendSql(")");
        }
        if (StringUtils.isNotBlank(clubName)) {  //club
            String[] clubsArray = clubName.split(";");
            sql.appendSql(" and(");
            for (int i = 0; i < clubsArray.length; i++) {
                String club = clubsArray[i];
                sql.appendSql("(club.name like ").appendValue("%" + club + "%").appendSql(")");
                if (i < clubsArray.length - 1) {
                    sql.appendSql(" or ");
                }
            }
            sql.appendSql(")");
        }
        if (StringUtils.isNotBlank(endDate)) { //endDate
            sql.appendSql(" and publish.end_date <=").appendValue(endDate);
        }
        if (timeStatus > 0) {    //推送状态
            String nowDate = DateUtils.format(new Date());
            switch (timeStatus) {
                case 1:
                    sql.appendSql(" and publish.start_date >").appendValue(nowDate);
                    break;
                case 2:
                    sql.appendSql(" and publish.start_date <=").appendValue(nowDate).appendSql(" and publish.end_date >=").appendValue(nowDate);
                    break;
                case 3:
                    sql.appendSql(" and publish.end_date <").appendValue(nowDate);
                    break;
            }
        }
        if (themeId > 0) {
            sql.appendSql(" and publish.theme_id =").appendValue(themeId);
        }

        sql.appendSql(" and promotion.status >=0");
        sql.appendSql(" order by promotion.").appendSql(geliOrm.getColumnByField(Promotion.class, orderField)).appendSql(" ").appendSql(orderDirection);
        Pager<Promotion> pager = pagerService.pager(Promotion.class, sql, pageNo, pageSize);
        if (pager != null && pager.getResultList() != null) {
            List<Promotion> list = pager.getResultList();
            for (Promotion p : list) {
                p.setPushRange(promotionService.getPushRange(p.getPromotionId()));
            }
        }

        String countSql = sql.getSql().replace(sql.getSql().substring(0, sql.getSql().toLowerCase().indexOf("from")), "select count(distinct(promotion.promotion_id)) ");
        int count = geliDao.count(countSql, sql.getValues());
        pager.setTotal(count);
        req.setAttribute("statusDesc", Promotion.statusDesc);
        req.setAttribute("pager", pager);
        List<Theme> themes = themeService.listAllThemes();
        req.setAttribute("themes", themes);
        return "admin/system/promotionList";
    }

    /**
     * @Description: 跳转到添加页面
     */
    @RequestMapping(value = "/promotion/showCreate.do", method = RequestMethod.GET)
    public String messageDetail(HttpServletRequest req, HttpServletResponse resp) {
        List<Theme> themes = themeService.listAllThemes();
        req.setAttribute("themes", themes);
        req.setAttribute("method", "create");
        return "admin/system/promotionDetail";
    }

    /**
     * @Description: 新增优惠活动
     */
    @RequestMapping(value = "/promotion/create.do", method = RequestMethod.POST)
    public String create(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        long adminId = GeliSession.getCurrentUser().getUserId();
        Promotion promotion = env.bind(Promotion.class);
        promotion.setCreateAt(DateUtils.getNow());
        promotion.setCreateBy(adminId);
        long promotionId = geliDao.create(promotion);
        if (promotionId <= 0) {
            errorMsg("创建失败，请联系管理员", resp);
            return null;
        }
        String[] provinceIds = req.getParameterValues("provinceIds");
        String[] cityIds = req.getParameterValues("cityIds");
        String[] brandIds = req.getParameterValues("brandIds");
        String[] serialsIds = req.getParameterValues("serialsIds");
        String[] provinceNames = req.getParameterValues("provinceNames");
        String[] cityNames = req.getParameterValues("cityNames");
        String[] brandNames = req.getParameterValues("brandNames");
        String[] serialsNames = req.getParameterValues("seriesNames");
        String[] clubIds = req.getParameterValues("clubIds");
        String[] themeIds = req.getParameterValues("themeIds");
        Date pushStart = DateUtils.parseDate(env.param("push_startDate"), "yyyy-MM-dd");
        Date pushEnd = DateUtils.parseDate(env.param("push_endDate"), "yyyy-MM-dd");
        // 品牌+地区 有值
        if (provinceIds != null && provinceIds.length > 0) {
            for (int i = 0; i < provinceIds.length; i++) {
                long provinceId = NumberUtils.toLong(provinceIds[i], 0);
                long cityId = NumberUtils.toLong(cityIds[i], 0);
                long brandId = NumberUtils.toLong(brandIds[i], 0);
                long serialsId = NumberUtils.toLong(serialsIds[i], 0);
                String provinceName = provinceNames[i];
                String cityName = cityNames[i];
                String brandName = brandNames[i];
                String serialsName = serialsNames[i];
                if (themeIds != null && themeIds.length > 0) {
                    for (int j = 0; j < themeIds.length; j++) {
                        long themeId = NumberUtils.toLong(themeIds[j], 0);
                        PromotionPublish promotionPublish = new PromotionPublish();
                        promotionPublish.setCreateAt(DateUtils.getNow());
                        promotionPublish.setCreateBy(adminId);
                        promotionPublish.setPromotionId(promotionId);
                        promotionPublish.setProvinceId(provinceId);
                        promotionPublish.setCityId(cityId);
                        promotionPublish.setBrandId(brandId);
                        promotionPublish.setProvinceName(provinceName);
                        promotionPublish.setCityName(cityName);
                        promotionPublish.setBrandName(brandName);
                        promotionPublish.setSeriesName(serialsName);
                        promotionPublish.setSerialId(serialsId);
                        promotionPublish.setThemeId(themeId);
                        promotionPublish.setStartDate(pushStart);
                        promotionPublish.setEndDate(pushEnd);
                        geliDao.create(promotionPublish);
                    }
                } else {
                    PromotionPublish promotionPublish = new PromotionPublish();
                    promotionPublish.setCreateAt(DateUtils.getNow());
                    promotionPublish.setCreateBy(adminId);
                    promotionPublish.setPromotionId(promotionId);
                    promotionPublish.setProvinceId(provinceId);
                    promotionPublish.setCityId(cityId);
                    promotionPublish.setBrandId(brandId);
                    promotionPublish.setSerialId(serialsId);
                    promotionPublish.setProvinceName(provinceName);
                    promotionPublish.setCityName(cityName);
                    promotionPublish.setBrandName(brandName);
                    promotionPublish.setSeriesName(serialsName);
                    promotionPublish.setStartDate(pushStart);
                    promotionPublish.setEndDate(pushEnd);
                    geliDao.create(promotionPublish);
                }
            }
        } else {
            if (themeIds != null && themeIds.length > 0) {
                for (int j = 0; j < themeIds.length; j++) {
                    long themeId = NumberUtils.toLong(themeIds[j], 0);
                    PromotionPublish promotionPublish = new PromotionPublish();
                    promotionPublish.setCreateAt(DateUtils.getNow());
                    promotionPublish.setCreateBy(adminId);
                    promotionPublish.setPromotionId(promotionId);
                    promotionPublish.setProvinceId(0);
                    promotionPublish.setCityId(0);
                    promotionPublish.setBrandId(0);
                    promotionPublish.setSerialId(0);
                    promotionPublish.setThemeId(themeId);
                    promotionPublish.setStartDate(pushStart);
                    promotionPublish.setEndDate(pushEnd);
                    geliDao.create(promotionPublish);
                }
            } else if (clubIds == null || clubIds.length <= 0) {  //什么都没有选择，默认全为0
                PromotionPublish promotionPublish = new PromotionPublish();
                promotionPublish.setCreateAt(DateUtils.getNow());
                promotionPublish.setCreateBy(adminId);
                promotionPublish.setPromotionId(promotionId);
                promotionPublish.setStartDate(pushStart);
                promotionPublish.setEndDate(pushEnd);
                geliDao.create(promotionPublish);
            }
        }
        // 选择了车友会
        if (clubIds != null && clubIds.length > 0) {
            for (int c = 0; c < clubIds.length; c++) {
                PromotionPublish promotionPublish = new PromotionPublish();
                promotionPublish.setCreateAt(DateUtils.getNow());
                promotionPublish.setCreateBy(adminId);
                promotionPublish.setPromotionId(promotionId);
                promotionPublish.setProvinceId(0);
                promotionPublish.setCityId(0);
                promotionPublish.setBrandId(0);
                promotionPublish.setSerialId(0);
                promotionPublish.setThemeId(0);
                promotionPublish.setClubId(NumberUtils.toLong(clubIds[c], 0));
                promotionPublish.setStartDate(pushStart);
                promotionPublish.setEndDate(pushEnd);
                geliDao.create(promotionPublish);
            }
        }
        successMsg("创建成功", "list-promotion", resp, "closeCurrent");
        return null;
    }

    @RequestMapping(value = "/promotion/club/list.do")
    public String listClub(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        //param
        String orderField = env.param("orderField", "audit_at");
        String orderDirection = env.param("orderDirection", "desc");
        String name = env.param("name", "").trim();
        long clubId = env.paramLong("clubId", 0);
        int pageNo = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        //sql
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select club_id from ").appendSql(geliOrm.getTableName(Club.class)).appendSql(" where 1=1 ");
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        if (StringUtils.isNotBlank(name)) {
            sql.appendSql(" and name like ").appendValue("%" + name + "%");
        }

        sql.appendSql(" and status = ").appendValue(Club.STATUS_PASS);
        sql.appendSql(" order by ").appendSql(geliOrm.getColumnByField(Club.class, orderField)).appendSql(" ").appendSql(orderDirection);
        Pager<Club> pager = pagerService.pager(Club.class, sql, pageNo, pageSize);
        req.setAttribute("pager", pager);
        req.setAttribute("name", name);
        req.setAttribute("clubId", clubId);
        req.setAttribute("orderField", orderField);
        req.setAttribute("orderDirection", orderDirection);
        return "admin/system/clubList";
    }

    /**
     * @Description: 上传方法
     * @param:
     * @return
     * @return: String
     */
    @RequestMapping(value = "/promotion/upload.do", method = RequestMethod.GET)
    public String upload(HttpServletRequest req, HttpServletResponse resp) {
        String command = req.getParameter("command");
        req.setAttribute("command", command);
        String picSource = req.getParameter("picSource");
        req.setAttribute("picSource", picSource);
        String perShow = req.getParameter("perShow");
        req.setAttribute("perShow", perShow);
        String showHref = req.getParameter("showHref");
        req.setAttribute("showHref", showHref);
        return "admin/system/upload";
    }

    /**
     * @Description: 删除方法（修改状态）
     * @param:
     * @return
     * @return: String
     */
    @RequestMapping(value = "/promotion/delete.do")
    public String delete(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        long id = env.paramLong("id", 0);
        if (id >= 0) {
            Promotion promotion = promotionService.findPromotion(id);
            promotion.setStatus(-1);
            promotionService.updatePromotion(promotion);
            successMsg("删除成功", "list-promotion", resp, "");
        } else {
            errorMsg("删除失败,请联系管理员", resp);
        }
        return null;
    }

    /**
     * @Description: 跳转修改方法
     * @param:
     * @return
     * @return: String
     */
    @RequestMapping(value = "/promotion/detail.do")
    public String detail(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long id = env.paramLong("id", 0);
        if (id >= 0) {
            Promotion promotion = promotionService.findPromotion(id);
            List<PromotionPublish> publishList = promotionService.listBypromotionId(id);
            List<Map<String, Object>> privinceBrandList = new ArrayList<Map<String, Object>>();
            List<Map<String, Object>> themeList = new ArrayList<Map<String, Object>>();
            List<Map<String, Object>> clubList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < publishList.size(); i++) {
                Map<String, Object> provinceBrandMap = new HashMap<String, Object>();
                Map<String, Object> themeMap = new HashMap<String, Object>();
                Map<String, Object> clubMap = new HashMap<String, Object>();
                PromotionPublish promotionPublish = publishList.get(i);
                String provinceName = promotionPublish.getProvinceName();
                long provinceId = promotionPublish.getProvinceId();
                String cityName = promotionPublish.getCityName();
                long cityId = promotionPublish.getCityId();
                String brandName = promotionPublish.getBrandName();
                long brandId = promotionPublish.getBrandId();
                String seriesName = promotionPublish.getSeriesName();
                long seriesId = promotionPublish.getSerialId();
                if (provinceId != 0 || cityId != 0 || seriesId != 0 || brandId != 0) {
                    boolean BPflag = false;
                    for (Map<String, Object> tempPB : privinceBrandList) {
                        long selectProvince = (Long) tempPB.get("provinceId");
                        long selectCity = (Long) tempPB.get("cityId");
                        long selectBrand = (Long) tempPB.get("brandId");
                        long selectSeries = (Long) tempPB.get("seriesId");
                        if (selectProvince == provinceId && selectCity == cityId && selectBrand == brandId && selectSeries == seriesId) {
                            BPflag = true;
                            break;
                        }
                    }
                    if (!BPflag) {
                        provinceBrandMap.put("name", provinceName + cityName + brandName + seriesName);
                        provinceBrandMap.put("provinceName", provinceName);
                        provinceBrandMap.put("provinceId", provinceId);
                        provinceBrandMap.put("cityName", cityName);
                        provinceBrandMap.put("cityId", cityId);
                        provinceBrandMap.put("brandName", brandName);
                        provinceBrandMap.put("brandId", brandId);
                        provinceBrandMap.put("seriesName", seriesName);
                        provinceBrandMap.put("seriesId", seriesId);
                        privinceBrandList.add(provinceBrandMap);
                    }
                }
                long themeId = promotionPublish.getThemeId();
                if (themeId > 0) {
                    Theme theme = geliDao.find(Theme.class, themeId);
                    if (theme != null) {
                        themeMap.put("themeId", themeId);
                        themeMap.put("themeName", theme.getThemeName());
                        boolean flag = false;
                        for (Map<String, Object> tempTheme : themeList) {
                            long tempThemeId = NumberUtils.toLong(tempTheme.get("themeId").toString(), 0);
                            if (themeId == tempThemeId) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            themeList.add(themeMap);
                        }
                    }
                }
                long clubId = promotionPublish.getClubId();
                if (clubId > 0) {
                    Club club = geliDao.find(Club.class, clubId);
                    if (club != null) {
                        clubMap.put("clubId", clubId);
                        clubMap.put("clubName", club.getName());
                        clubList.add(clubMap);
                    }
                }
            }

            List<Theme> themes = themeService.listAllThemes();
            req.setAttribute("themes", themes);
            req.setAttribute("privinceBrandList", privinceBrandList);
            req.setAttribute("themeList", themeList);
            req.setAttribute("clubList", clubList);
            req.setAttribute("method", "update");
            req.setAttribute("promotion", promotion);
            req.setAttribute("publishList", publishList);

        } else {
            errorMsg("操作失败,请联系管理员", resp);
        }

        return "admin/system/promotionDetail";
    }

    /**
     * @Description: 修改方法
     * @param:
     * @return
     * @return: String
     */
    @RequestMapping(value = "/promotion/update.do", method = RequestMethod.POST)
    public String update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        GeliLogFacade.log();
        Env env = EnvUtils.getEnv();
        long adminId = GeliSession.getCurrentUser().getUserId();
        long promotionId = env.paramLong("promotionId", 0);
        if (promotionId > 0) {
            Promotion promotion = promotionService.findPromotion(promotionId);
            if (promotion == null) {
                successMsg("修改失败,优惠不存在", "list-promotion", resp, "closeCurrent");
                return null;
            }
            env.bind(Promotion.class, promotion);
            promotion.setUpdateAt(DateUtils.getNow());
            promotion.setUpdateBy(adminId);
            geliDao.update(promotion);
            List<PromotionPublish> publishs = promotionService.listBypromotionId(promotionId);
            //删除原有数据
            for (int i = 0; i < publishs.size(); i++) {
                geliDao.delete(publishs.get(i), publishs.get(i).getPublishId());
            }
            //新增数据
            String[] provinceIds = req.getParameterValues("provinceIds");
            String[] cityIds = req.getParameterValues("cityIds");
            String[] brandIds = req.getParameterValues("brandIds");
            String[] serialsIds = req.getParameterValues("serialsIds");
            String[] provinceNames = req.getParameterValues("provinceNames");
            String[] cityNames = req.getParameterValues("cityNames");
            String[] brandNames = req.getParameterValues("brandNames");
            String[] serialsNames = req.getParameterValues("seriesNames");
            String[] clubIds = req.getParameterValues("clubIds");
            String[] themeIds = req.getParameterValues("themeIds");
            Date pushStart = DateUtils.parseDate(env.param("push_startDate"), "yyyy-MM-dd");
            Date pushEnd = DateUtils.parseDate(env.param("push_endDate"), "yyyy-MM-dd");
            // 品牌+地区 有值
            if (provinceIds != null && provinceIds.length > 0) {
                for (int i = 0; i < provinceIds.length; i++) {
                    long provinceId = NumberUtils.toLong(provinceIds[i], 0);
                    long cityId = NumberUtils.toLong(cityIds[i], 0);
                    long brandId = NumberUtils.toLong(brandIds[i], 0);
                    long serialsId = NumberUtils.toLong(serialsIds[i], 0);
                    String provinceName = provinceNames[i];
                    String cityName = cityNames[i];
                    String brandName = brandNames[i];
                    String serialsName = serialsNames[i];
                    if (themeIds != null && themeIds.length > 0) {
                        for (int j = 0; j < themeIds.length; j++) {
                            long themeId = NumberUtils.toLong(themeIds[j], 0);
                            PromotionPublish promotionPublish = new PromotionPublish();
                            promotionPublish.setUpdateAt(DateUtils.getNow());
                            promotionPublish.setUpdateBy(adminId);
                            promotionPublish.setPromotionId(promotionId);
                            promotionPublish.setProvinceId(provinceId);
                            promotionPublish.setCityId(cityId);
                            promotionPublish.setBrandId(brandId);
                            promotionPublish.setProvinceName(provinceName);
                            promotionPublish.setCityName(cityName);
                            promotionPublish.setBrandName(brandName);
                            promotionPublish.setSeriesName(serialsName);
                            promotionPublish.setSerialId(serialsId);
                            promotionPublish.setThemeId(themeId);
                            promotionPublish.setStartDate(pushStart);
                            promotionPublish.setEndDate(pushEnd);
                            geliDao.create(promotionPublish);
                        }
                    } else {
                        PromotionPublish promotionPublish = new PromotionPublish();
                        promotionPublish.setUpdateAt(DateUtils.getNow());
                        promotionPublish.setUpdateBy(adminId);
                        promotionPublish.setPromotionId(promotionId);
                        promotionPublish.setProvinceId(provinceId);
                        promotionPublish.setCityId(cityId);
                        promotionPublish.setBrandId(brandId);
                        promotionPublish.setSerialId(serialsId);
                        promotionPublish.setProvinceName(provinceName);
                        promotionPublish.setCityName(cityName);
                        promotionPublish.setBrandName(brandName);
                        promotionPublish.setSeriesName(serialsName);
                        promotionPublish.setStartDate(pushStart);
                        promotionPublish.setEndDate(pushEnd);
                        geliDao.create(promotionPublish);
                    }
                }
            } else {
                if (themeIds != null && themeIds.length > 0) {
                    for (int j = 0; j < themeIds.length; j++) {
                        long themeId = NumberUtils.toLong(themeIds[j], 0);
                        PromotionPublish promotionPublish = new PromotionPublish();
                        promotionPublish.setUpdateAt(DateUtils.getNow());
                        promotionPublish.setUpdateBy(adminId);
                        promotionPublish.setPromotionId(promotionId);
                        promotionPublish.setProvinceId(0);
                        promotionPublish.setCityId(0);
                        promotionPublish.setBrandId(0);
                        promotionPublish.setSerialId(0);
                        promotionPublish.setThemeId(themeId);
                        promotionPublish.setStartDate(pushStart);
                        promotionPublish.setEndDate(pushEnd);
                        geliDao.create(promotionPublish);
                    }
                } else if (clubIds == null || clubIds.length <= 0) { //什么都没有选择，默认全为0
                    PromotionPublish promotionPublish = new PromotionPublish();
                    promotionPublish.setCreateAt(DateUtils.getNow());
                    promotionPublish.setCreateBy(adminId);
                    promotionPublish.setPromotionId(promotionId);
                    promotionPublish.setStartDate(pushStart);
                    promotionPublish.setEndDate(pushEnd);
                    geliDao.create(promotionPublish);
                }
            }
            // 选择了车友会
            if (clubIds != null && clubIds.length > 0) {
                for (int c = 0; c < clubIds.length; c++) {
                    PromotionPublish promotionPublish = new PromotionPublish();
                    promotionPublish.setUpdateAt(DateUtils.getNow());
                    promotionPublish.setUpdateBy(adminId);
                    promotionPublish.setPromotionId(promotionId);
                    promotionPublish.setProvinceId(0);
                    promotionPublish.setCityId(0);
                    promotionPublish.setBrandId(0);
                    promotionPublish.setSerialId(0);
                    promotionPublish.setThemeId(0);
                    promotionPublish.setClubId(NumberUtils.toLong(clubIds[c], 0));
                    promotionPublish.setStartDate(pushStart);
                    promotionPublish.setEndDate(pushEnd);
                    geliDao.create(promotionPublish);
                }
            }
        }
        successMsg("修改成功", "list-promotion", resp, "closeCurrent");
        return null;
    }

    private void successMsg(String msg, String navTabId, HttpServletResponse resp, String callbackType) {
        try {
            String rs = StringUtils.isEmpty(msg) ? "操作成功" : msg;
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(new JSONBuilder()
                    .put("statusCode", 200)
                    .put("message", rs)
                    .put("navTabId", navTabId)
                    .put("callbackType", callbackType)
                    .toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    private void errorMsg(String msg, HttpServletResponse resp) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", 300)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }
}
